package com.ibeeking.gateway.cp.config.filter;

import com.ibeeking.gateway.cp.config.uaa.WhiteListConfig;
import com.ibeeking.found.common.constants.HeaderNounConstant;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * 白名单路径访问时需要移除请求头认证信息
 *
 * @author ibeeking
 */
@Component
@RefreshScope
public class DefaultWebFilter implements WebFilter {
    private static final String ALL = "*";

    @Resource
    private WhiteListConfig properties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径移除请求头认证信息
        String authorization = request.getHeaders().getFirst(HeaderNounConstant.AUTHORIZATION);
        List<String> urls = properties.getUrls();
        for (String url : urls) {
            if (!pathMatcher.match(url, path)) {
                request = exchange.getRequest().mutate().header(HeaderNounConstant.AUTHORIZATION, authorization).build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }
}